package cn.com.infcn.monitor.task.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import cn.com.infcn.monitor.bean.IFCNet;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;

/**
 * 获取网络相关信息
 * 
 * @author jijs
 *
 */
public class NetTask implements BaseTask {

	private static final Logger LOGGER = Logger.getLogger(NetTask.class);

	@Override
	public List<IFCNet> execute() throws Exception {
		return net();
	}

	private List<IFCNet> net() throws SigarException {
		try {
			Sigar sigar = new Sigar();
			String ifNames[] = sigar.getNetInterfaceList();

			List<IFCNet> nets = new ArrayList<IFCNet>();

			for (int i = 0; i < ifNames.length; i++) {
				IFCNet net = new IFCNet();
				String name = ifNames[i];
				NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
				if (NetFlags.LOOPBACK_ADDRESS.equals(ifconfig.getAddress())
						|| (ifconfig.getFlags() & NetFlags.IFF_LOOPBACK) != 0
						|| NetFlags.NULL_HWADDR.equals(ifconfig.getHwaddr())) {
					continue;
				}

				IFCBeanUtils.copyProperties(ifconfig, net);

				if ((ifconfig.getFlags() & 1L) <= 0L) {
//					System.out.println("!IFF_UP...skipping getNetInterfaceStat");
					continue;
				}

				NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
				IFCBeanUtils.copyProperties(ifstat, net);
				nets.add(net);
			}

			return nets;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}
		return null;
	}

	/*private void copyProperties(NetInterfaceConfig ifconfig, IFCNet net){
		net.setAddress(ifconfig.getAddress());
		net.setBroadcast(ifconfig.getBroadcast());
		
		net.setDescription(ifconfig.getDescription());
		net.setDestination(ifconfig.getDestination());
		net.setFlags(ifconfig.getFlags());
		net.setHwaddr(ifconfig.getHwaddr());
		net.setMetric(ifconfig.getMetric());
		net.setMtu(ifconfig.getMtu());
		net.setName(ifconfig.getName());
		net.setNetmask(ifconfig.getNetmask());
		net.setType(ifconfig.getType());
	}
	
	private void copyProperties(NetInterfaceStat ifstat, IFCNet net){
		net.setRxBytes(ifstat.getRxBytes());
		net.setRxDropped(ifstat.getRxDropped());
		net.setRxErrors(ifstat.getRxErrors());
		net.setRxFrame(ifstat.getRxFrame());
		net.setRxOverruns(ifstat.getRxOverruns());
		net.setRxPackets(ifstat.getRxPackets());
		net.setSpeed(ifstat.getSpeed());
		net.setTxBytes(ifstat.getTxBytes());
		net.setTxCarrier(ifstat.getTxCarrier());
		net.setTxCollisions(ifstat.getTxCollisions());
		net.setTxDropped(ifstat.getTxDropped());
		net.setTxErrors(ifstat.getTxErrors());
		net.setTxOverruns(ifstat.getTxOverruns());
		net.setTxPackets(ifstat.getTxPackets());
	}*/
}
